package classify

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"sola/common"
	"sola/db"
	"sola/router/middleware"
	"sola/utils"
	"strconv"
)

func create(c *gin.Context) {
	var classify db.Classify
	if err := c.ShouldBind(&classify); err != nil {
		fmt.Println("ShouldBind", err)
		utils.ResponseError(c, utils.ErrCodeParameter)
		return
	}
	user, err := middleware.GetUser(c)
	if err != nil {
		utils.ResponseError(c, utils.ErrCodeUserNotExist)
		return
	}
	classify.AuthorId = user.UserId
	classify.AuthorName = user.Username
	classify.AuthorNickName = user.Nickname
	classify.UpdateUserId = user.UserId
	classify.UpdateUserName = user.Username
	classify.UpdateUserNickName = user.Nickname
	classify.AuthorName = "admin"
	classify.Changeable = true
	db.Creaete(&classify)
	utils.ResponseSuccess(c, &classify)
	return
}

func update(c *gin.Context) {
	var classify db.Classify
	if err := c.ShouldBind(&classify); err != nil {
		fmt.Println("ShouldBind", err)
		utils.ResponseError(c, utils.ErrCodeParameter)
		return
	}
	user, err := middleware.GetUser(c)
	if err != nil {
		utils.ResponseError(c, utils.ErrCodeUserNotExist)
		return
	}
	classify.AuthorId = user.UserId
	classify.AuthorName = user.Username
	classify.AuthorNickName = user.Nickname
	classify.UpdateUserId = user.UserId
	classify.UpdateUserName = user.Username
	classify.UpdateUserNickName = user.Nickname
	db.Update(&classify)
	utils.ResponseSuccess(c, &classify)
	return
}

func list(c *gin.Context) {
	var baseSearchModel common.BaseSearchModel
	if err := c.ShouldBind(&baseSearchModel); err != nil {
		fmt.Println("ShouldBind", err)
		utils.ResponseError(c, utils.ErrCodeParameter)
		return
	}
	if err := c.ShouldBindUri(&baseSearchModel); err != nil {
		fmt.Println("ShouldBind", err)
		utils.ResponseError(c, utils.ErrCodeParameter)
		return
	}
	if baseSearchModel.UserId == "" {
		utils.ResponseError(c, utils.ErrCodeParameter)
		return
	}
	data := make(map[string]interface{})
	count := db.CountClassify(&baseSearchModel)
	//var classifies []db.Classify
	classifies := db.GetClassifyList(&baseSearchModel)
	data["total"] = count
	data["items"] = classifies
	utils.ResponseSuccess(c, data)
	return
}

func detail(c *gin.Context) {
	c.Request.ParseForm()
	id_str := c.Request.Form.Get("id")
	id, err := strconv.Atoi(id_str)
	if err != nil {
		utils.ResponseError(c, utils.ErrCodeParameter)
	}
	var classify = db.Classify{
		BaseModel: common.BaseModel{Id: uint(id)},
	}
	db.First(&classify)
	fmt.Println("classify:", classify)
	utils.ResponseSuccess(c, &classify)
	return
}

func delete(c *gin.Context) {
	var classify db.Classify
	if err := c.ShouldBindUri(&classify); err != nil {
		fmt.Println("ShouldBind", err)
		utils.ResponseError(c, utils.ErrCodeParameter)
		return
	}
	db.Delete(&classify)
	utils.ResponseSuccess(c, &classify)
	return
}
